package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.dao.ESManagerMapper;
import com.changgou.goods.feign.GoodsFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
@Service
public class ESManagerServiceImpl implements ESManagerService {

	@Autowired
	private ElasticsearchTemplate elasticsearchTemplate;
	@Autowired
	private GoodsFeign skuFeign;
	@Autowired
	private ESManagerMapper esManagerMapper;
	@Override
	public void createIndexAndMapping() {
		elasticsearchTemplate.createIndex(SkuInfo.class);
		elasticsearchTemplate.putMapping(SkuInfo.class);
	}

	@Override
	public void importAll() {
		List<Sku> skuList = skuFeign.findSkuListBySpuId("all");
		if(skuList==null||skuList.size()<=0){
			throw new RuntimeException("没有查到数据");
		}
		//skuList转换为json
		String jsonSkuList = JSON.toJSONString(skuList);
		//将json转换成SkuInFo
		List<SkuInfo> skuInfoList = JSON.parseArray(jsonSkuList, SkuInfo.class);
		for (SkuInfo skuInfo : skuInfoList) {
			//将规格信息转换为map
			Map specMap = JSON.parseObject(skuInfo.getSpec(),Map.class);
			skuInfo.setSpecMap(specMap);
		}
		//导入索引库
		esManagerMapper.saveAll(skuInfoList);
	}
	//根据spuId查询skuList,添加到索引库
	@Override
	public void importDataToESBySpuId(String spuId) {
		List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
		if(skuList==null||skuList.size()<=0){
			throw new RuntimeException("没有查到数据");
		}
		//skuList转换为json
		String jsonSkuList = JSON.toJSONString(skuList);
		//将json转换成SkuInFo
		List<SkuInfo> skuInfoList = JSON.parseArray(jsonSkuList, SkuInfo.class);
		for (SkuInfo skuInfo : skuInfoList) {
			//将规格信息转换为map
			Map specMap = JSON.parseObject(skuInfo.getSpec(),Map.class);
			skuInfo.setSpecMap(specMap);
		}
		//导入索引库
		esManagerMapper.saveAll(skuInfoList);
	}

	@Override
	public void delDataBySpuId(String spuId) {
		List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
		if(skuList==null||skuList.size()<=0){
			throw new RuntimeException("没有查到数据");
		}
		for (Sku sku : skuList) {
			esManagerMapper.deleteById(Long.parseLong(sku.getId()));
		}
	}
}
